#!/bin/bash

# stop_tunnel.sh - Script to stop the reverse SSH tunnel started by reverse_tunnel.sh

# --- Configuration - Read from config file to get PID file name convention ---
CONFIG_FILE="./config.sh"

if [ ! -f "${CONFIG_FILE}" ]; then
    echo "Error: Configuration file '${CONFIG_FILE}' not found."
    echo "This script needs it to determine the PID file based on REMOTE_PORT_FORWARD."
    echo "Make sure you are in the same directory as your config.sh and reverse_tunnel.sh."
    exit 1
fi

source "${CONFIG_FILE}"

if [ -z "${REMOTE_PORT_FORWARD}" ]; then
    echo "Error: REMOTE_PORT_FORWARD is not set in '${CONFIG_FILE}'. Cannot determine PID file."
    exit 1
fi

AUTOSSH_PIDFILE="/tmp/autossh_reverse_tunnel_${REMOTE_PORT_FORWARD}.pid"

echo "Attempting to stop the reverse SSH tunnel..."

if [ -f "${AUTOSSH_PIDFILE}" ]; then
    PID_TO_KILL=$(cat "${AUTOSSH_PIDFILE}")
    if ps -p "${PID_TO_KILL}" > /dev/null; then
        echo "Found running autossh process with PID ${PID_TO_KILL} (from ${AUTOSSH_PIDFILE})."
        # Attempt graceful termination first
        kill "${PID_TO_KILL}"
        sleep 2 # Give it a moment to terminate

        if ps -p "${PID_TO_KILL}" > /dev/null; then
            echo "Process ${PID_TO_KILL} still running. Sending SIGKILL."
            kill -9 "${PID_TO_KILL}"
            sleep 1
        fi

        if ps -p "${PID_TO_KILL}" > /dev/null; then
            echo "Error: Failed to kill process ${PID_TO_KILL}. Please check manually."
            exit 1
        else
            echo "Process ${PID_TO_KILL} stopped successfully."
            rm -f "${AUTOSSH_PIDFILE}"
            echo "PID file ${AUTOSSH_PIDFILE} removed."
        fi
    else
        echo "Process with PID ${PID_TO_KILL} (from ${AUTOSSH_PIDFILE}) not found or already stopped."
        echo "Removing stale PID file: ${AUTOSSH_PIDFILE}"
        rm -f "${AUTOSSH_PIDFILE}"
    fi
else
    echo "PID file ${AUTOSSH_PIDFILE} not found. No specific autossh process to stop for this configuration."
    echo "If autossh is running but the PID file is missing, you may need to find and stop it manually."
    echo "You can try: pgrep -lf 'autossh.*-R ${REMOTE_PORT_FORWARD}:'"
    echo "And then: kill <PID>"
fi

# General cleanup for any autossh process that might be lingering for this port (less precise)
# This is a fallback in case the PID file method fails or is not available.
# It's commented out by default to avoid accidentally killing unrelated processes if the port number is generic.
# Consider enabling if you face issues with orphaned processes.
# echo "Searching for other potential autossh processes for port ${REMOTE_PORT_FORWARD}..."
# pkill -f "autossh.*-R ${REMOTE_PORT_FORWARD}:localhost:${LOCAL_PORT_TO_FORWARD}.*${REMOTE_USER}@${REMOTE_HOST}"
# sleep 1
# if pgrep -f "autossh.*-R ${REMOTE_PORT_FORWARD}:localhost:${LOCAL_PORT_TO_FORWARD}.*${REMOTE_USER}@${REMOTE_HOST}" > /dev/null; then
# echo "Some autossh processes might still be running. Please check manually."
# else
# echo "General cleanup for port ${REMOTE_PORT_FORWARD} seems successful or no processes were found."
# fi

echo "Tunnel stop script finished."
exit 0

